package com.idanchuang.component.businesslog.es.index;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.indexlifecycle.GetLifecyclePolicyRequest;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * The IndexStateManagerRequestConverters
 *
 * @since 2020/7/17
 */
public class IndexManageConverters {

    private IndexManageConverters() {}

    static Request getLifecyclePolicy(GetLifecyclePolicyRequest getLifecyclePolicyRequest) {
        String endpoint = new IndexManageRequest()
                .addPathPartAsIs("_opendistro/_ism/policies")
                .addCommaSeparatedPathParts(getLifecyclePolicyRequest.getPolicyNames())
                .build();
        Request request = new Request(HttpGet.METHOD_NAME, endpoint);
        Map<String,String> params = new HashMap<>();
        params.put("master_timeout", getLifecyclePolicyRequest.masterNodeTimeout().getStringRep());
        params.put("timeout", getLifecyclePolicyRequest.timeout().getStringRep());
        request.addParameters(params);
        return request;
    }

    static Request putLifecyclePolicy(PutIndexManagerPolicyRequest putLifecycleRequest) throws IOException {
        String endpoint = new IndexManageRequest()
                .addPathPartAsIs("_opendistro/_ism/policies")
                .addPathPartAsIs(putLifecycleRequest.getName())
                .build();
        Request request = new Request(HttpPut.METHOD_NAME, endpoint);
        Map<String,String> params = new HashMap<>();
        params.put("master_timeout", putLifecycleRequest.masterNodeTimeout().getStringRep());
        params.put("timeout", putLifecycleRequest.timeout().getStringRep());
        request.addParameters(params);
        request.setEntity(IndexManageRequest.createEntity(putLifecycleRequest, XContentType.JSON));
        return request;
    }
}
